package com.niu.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.niu.constant.MessageConstant;
import com.niu.constant.StatusConstant;
import com.niu.dto.ProductDTO;
import com.niu.dto.ProductPageQueryDTO;
import com.niu.entity.Product;
import com.niu.exception.DeletionNotAllowedException;
import com.niu.mapper.ProductMapper;
import com.niu.result.PageResult;
import com.niu.service.ProductService;
import com.niu.vo.ProductVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;
    /**
     * 新增商品
     * @param productDTO
     */
    @Transactional
    @Override
    public void savewith(ProductDTO productDTO) {

        Product product = new Product();
        BeanUtils.copyProperties(productDTO, product);

        //向商品表插入数据
        productMapper.insert(product);

    }

    /**
     * 商品分页查询
     * @param productPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(ProductPageQueryDTO productPageQueryDTO) {
        PageHelper.startPage(productPageQueryDTO.getPage(), productPageQueryDTO.getPageSize());
        Page<ProductVO> page = productMapper.pageQuery(productPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 商品批量删除
     * @param ids
     */
    @Transactional
    @Override
    public void deleteBatch(List<Long> ids) {
        //判断当前商品能不能删除---是否存在起售菜品
        for (Long id : ids) {
            Product product =  productMapper.getById(id);
            if(product.getStatus() == StatusConstant.ENABLE){
                //当前商品在起售中，不能删除
                throw new DeletionNotAllowedException(MessageConstant.SNACK_ON_SALE);
            }
        }

        //根据商品id集合批量删除商品数据
        //sql:delete from snack where id in (?, ?, ?)
        productMapper.deleteByIds(ids);

    }


    /**
     * 根据id修改商品
     * @param productDTO
     */
    @Override
    public void updateWith(ProductDTO productDTO) {
        Product product = new Product();
        BeanUtils.copyProperties(productDTO, product);

        //修改商品基本信息
        productMapper.update(product);
    }


    /**
     * 商品起售，停售
     * @param status
     * @param id
     */
    @Override
    public void status(Integer status, Long id) {
        Product product = new Product();
        product.setStatus(status);
        product.setId(id);
        productMapper.update(product);
    }
}
